package com.example.demo.config.shiro;

import com.example.demo.entity.access.User;
import com.example.demo.service.access.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 这个是实现rememberMe功能的form登录过滤器  主要是防止session 里面user为空
 */
public class RememberMeFormAuthenticationFilter extends FormAuthenticationFilter {
    private transient static final Logger LOGGER = LoggerFactory.getLogger(RememberMeFormAuthenticationFilter.class);

    private IUserService userService;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {

        Subject subject = SecurityUtils.getSubject();

        // 如果没有登录认证 但是 使用了记住我的功能 记住了
        if (!subject.isAuthenticated() && subject.isRemembered()) {
            Session session = subject.getSession(true);

            User user = null;
            if (session.getAttribute("user") instanceof User) {
                user = (User) session.getAttribute("user");
            }
            if (user == null) {
                Object username = subject.getPrincipal();
                if (username != null) {
                    user = userService.findByUsername(username.toString());
                    if (user != null) {
                        session.setAttribute("user", user);
                        LOGGER.info("用户:{}使用rememberMe功能进入系统", user);
                    }
                }
            }
        }

        return subject.isAuthenticated() || subject.isRemembered();
    }

    public IUserService getUserService() {
        return userService;
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }
}
